#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    echo -e "${GREEN}[INFO] $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}[WARNING] $1${NC}"
}

print_error() {
    echo -e "${RED}[ERROR] $1${NC}"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_error "$1 未安装，请先安装 $1"
        exit 1
    fi
}

# 检查必要的命令
check_command java
check_command mvn
check_command mysql
check_command redis-cli
check_command nginx

# 检查Java版本
java_version=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')
print_message "检测到Java版本: $java_version"

# 检查MySQL连接
print_message "正在检查MySQL连接..."
if mysql -u root -p -e "SELECT 1" &> /dev/null; then
    print_message "MySQL连接成功"
else
    print_error "MySQL连接失败，请检查MySQL服务是否运行"
    exit 1
fi

# 检查Redis连接
print_message "正在检查Redis连接..."
if redis-cli ping &> /dev/null; then
    print_message "Redis连接成功"
else
    print_error "Redis连接失败，请检查Redis服务是否运行"
    exit 1
fi

# 部署后端
deploy_backend() {
    print_message "开始部署后端..."
    cd backend
    print_message "编译打包后端..."
    mvn clean package -DskipTests
    if [ $? -ne 0 ]; then
        print_error "后端编译失败"
        exit 1
    fi
    print_message "后端编译成功"
    
    # 停止现有服务（如果有）
    if pgrep -f "bi-platform-backend" > /dev/null; then
        print_message "停止现有后端服务..."
        pkill -f "bi-platform-backend"
    fi
    
    # 启动新服务
    print_message "启动后端服务..."
    nohup java -jar target/bi-platform-backend-1.0.0.jar > /dev/null 2>&1 &
    
    # 检查服务是否成功启动
    sleep 5
    if pgrep -f "bi-platform-backend" > /dev/null; then
        print_message "后端服务启动成功"
    else
        print_error "后端服务启动失败，请检查日志"
        exit 1
    fi
    
    cd ..
}

# 部署前端
deploy_frontend() {
    print_message "开始部署前端..."
    cd frontend
    print_message "安装前端依赖..."
    npm install
    if [ $? -ne 0 ]; then
        print_error "前端依赖安装失败"
        exit 1
    fi
    
    print_message "构建前端..."
    npm run build
    if [ $? -ne 0 ]; then
        print_error "前端构建失败"
        exit 1
    fi
    print_message "前端构建成功"
    
    # 部署到Nginx
    print_message "部署前端到Nginx..."
    sudo cp -r dist/* /var/www/html/bi-platform/
    if [ $? -ne 0 ]; then
        print_error "前端部署失败，请检查Nginx配置"
        exit 1
    fi
    
    # 重启Nginx
    print_message "重启Nginx..."
    sudo systemctl restart nginx
    if [ $? -ne 0 ]; then
        print_error "Nginx重启失败"
        exit 1
    fi
    
    cd ..
    print_message "前端部署成功"
}

# 主函数
main() {
    print_message "开始部署BI平台..."
    
    # 部署后端
    deploy_backend
    
    # 部署前端
    deploy_frontend
    
    print_message "BI平台部署完成！"
    print_message "后端API地址: http://localhost:8080/api"
    print_message "前端访问地址: http://localhost"
}

# 执行主函数
main